package cn.roadtrip.mtravelbusinessmodule.util.api.ins;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.roadtrip.mtravelbusinessmodule.util.api.ins.model.InsData;
import cn.roadtrip.mtravelbusinessmodule.util.api.ins.model.TokenResult;
import cn.roadtrip.mtravelbusinessmodule.util.api.ins.model.TrialOrderPriceRequest;
import cn.roadtrip.utilmodule.util.DataBean;
import com.google.gson.Gson;
import jakarta.annotation.PostConstruct;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 第三方保险工具
 */
@Component
@Slf4j
public class InsuranceImpl {

    @Autowired
    private StringRedisTemplate redisTemplate;
    private String userName = "apitest24314";
    private String passWord = "apitest24314";
    private String REDIS_KEY = "INSURANCE_TOKEN";

    private final String DOMAIN = "https://testapi.51baoy.com/InsApi";
    private final String TOKEN_URL = DOMAIN + "/Oauth/access_token";
    private final String CREATEINS_URL = DOMAIN + "/Insurance/Insuran";
    private final String GETPRODUCTLIST_URL = DOMAIN + "/ApiProduct/v2/GetProductList";
    private final String CALORDERPRICE_URL = DOMAIN + "/Order/TrialOrderPrice";//计算价格
    private final String PRODUCTDETAIL_URL = DOMAIN + "/ApiProduct/v2/GetProductDetail";//保险详情


    @PostConstruct
    public void init() {
        getToken();
    }

    //    @Scheduled(fixedDelay = (600800), timeUnit = TimeUnit.SECONDS)
    public TokenResult getToken() {
        String token = HttpUtil.get(TOKEN_URL + "?userid=" + userName + "&Password=" + passWord);
        log.info("保险token:" + token);
        redisTemplate.opsForValue().set(REDIS_KEY, token);
        return new Gson().fromJson(token, TokenResult.class);
    }

    /**
     * 创建保单
     *
     * @param insData
     * @return
     */
    public String createInsurane(
            InsData insData
    ) {
        log.info("投保数据->{}", new Gson().toJson(insData));
        String tokenstr = redisTemplate.opsForValue().get(REDIS_KEY);
        TokenResult r = new Gson().fromJson(tokenstr, TokenResult.class);
        String rs = null;
        try {
            log.info("使用token->{}", r.getAccessToken());
//            rs = HttpUtil.post(CREATEINS_URL, Map.of(
//                    "token", URLEncoder.encode(r.getAccessToken())
//                    , "jsonParam", URLEncoder.encode(new Gson().toJson(insData), "utf-8")
//            ));
            log.info("保险值：{}", new Gson().toJson(insData));
            rs = HttpUtil.post(CREATEINS_URL, Map.of(
                    "token", r.getAccessToken()
                    , "jsonParam", new Gson().toJson(insData)
            ));
            log.info("创建保单：{}", rs);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return rs;
    }

    /**
     * 获取产品列表
     *
     * @return
     */
    public String getProductList() {
        String tokenstr = redisTemplate.opsForValue().get(REDIS_KEY);
        TokenResult r = new Gson().fromJson(tokenstr, TokenResult.class);
        String rs = null;
        try {
            log.info("使用token->{}", r.getAccessToken());
//            rs = HttpUtil.post(CREATEINS_URL, Map.of(
//                    "token", URLEncoder.encode(r.getAccessToken())
//                    , "jsonParam", URLEncoder.encode(new Gson().toJson(insData), "utf-8")
//            ));
            rs = HttpUtil.post(GETPRODUCTLIST_URL, Map.of(
                    "token", r.getAccessToken()
                    , "tokenCode", r.getTokenCode()
                    , "pageIndex", 1,
                    "pageSize", 20
            ));
            log.info("获取产品列表：{}", rs);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return rs;
    }

    /**
     * 计算费用
     *
     * @param model
     * @return
     */
    public String calOrderPrice(TrialOrderPriceRequest model) {
        log.info("请求计算价请求体：{}", new Gson().toJson(model));
        String tokenstr = redisTemplate.opsForValue().get(REDIS_KEY);
        TokenResult r = new Gson().fromJson(tokenstr, TokenResult.class);
        String rs = null;
        model.setAccessToken(r.getAccessToken());
        model.setTokenCode(r.getTokenCode());
        try {
            log.info("使用token->{}", r.getAccessToken());
//            rs = HttpUtil.post(CREATEINS_URL, Map.of(
//                    "token", URLEncoder.encode(r.getAccessToken())
//                    , "jsonParam", URLEncoder.encode(new Gson().toJson(insData), "utf-8")
//            ));
            rs = HttpUtil.post(CALORDERPRICE_URL,
                    Map.of(
                            "jsonParam", new Gson().toJson(model)
                    )
            );
            log.info("计算价格：{}", rs);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return rs;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    @EqualsAndHashCode
    public static class ModelgetInsuranceDetail {
        private String productGuid;
    }

    /**
     * 查看合同详情
     *
     * @param model
     * @return
     */
    @SneakyThrows
    public DataBean getInsuranceDetail(ModelgetInsuranceDetail model) {

        String tokenstr = redisTemplate.opsForValue().get(REDIS_KEY);
        TokenResult r = new Gson().fromJson(tokenstr, TokenResult.class);
        String rs = null;
        HttpResponse rps = HttpUtil.createPost(PRODUCTDETAIL_URL).form(Map.of(
                "token", r.getAccessToken()
                , "tokenCode", r.getTokenCode(),
                "productGuid", model.getProductGuid()
        )).execute();

        System.out.println("token->" + r.getAccessToken());
        System.out.println("tokenCode->" + r.getTokenCode());
        System.out.println("productGuid->" + model.getProductGuid());
        System.out.println(rps.contentEncoding());
        rs = rps.body();
        System.out.println(rs);

//        return new String(rs.getBytes("ISO-8859-1"), StandardCharsets.UTF_8);
//        return rs;
//        return "这是字符";
        return DataBean.suc(new Gson().fromJson(rs,Map.class),1,"suc","操作成功");
    }

}
